#/bin/bash
function log_print()
{
    local log_msg=""
    local log_level="$1"
    local log_color=""
    local time_stamp=""

    if [ "${log_level}" = "ERROR" ]
    then
        log_color="31"
    elif [ "${log_level}" = "INFO" ]
    then
        log_color="32"
    else
        log_color="0"
    fi

    time_stamp=$(date "+%Y-%m-%d %H:%M:%S")
    log_msg="[${time_stamp}][${log_level}] ${2}"
    echo -e "\033[${log_color}m${log_msg}\033[0m"
}

function eval_cmd()
{
    log_print "INFO" "$1"
    eval "$1"
}

function remove_module()
{
    local mod_name="$1"
    local mod_status=""
    mod_status=$(lsmod | grep ${mod_name} | awk '{ print $1 }')
    if [ ! "${mod_status}" = "" ]
    then
        rmmod "${mod_name}" > /dev/null 2>&1
    fi
    return 0
}

function build_module()
{
    clear
    make clean

    make
    if [ $? -ne 0 ]
    then
        log_print "ERROR" "Build failed."
        exit 1
    fi
    log_print "INFO" "Built successfully."
    return 0
}

function load_module()
{
    log_print "INFO" "Start load module."

    # remove_module "v_device"
    # remove_module "v_driver"
    # remove_module "v_bus"

    dmesg -c > /dev/null 2>&1

    insmod v_bus.ko
    # insmod v_driver.ko
    # insmod v_device.ko

    dmesg

    eval_cmd "ls /sys/bus/vbus"
    eval_cmd "ls /sys/bus/vbus/drivers"
    eval_cmd "ls /sys/bus/vbus/drivers/vdriver"
    eval_cmd "ls /sys/bus/vbus/devices"
    eval_cmd "ls /sys/bus/vbus/devices/vdevice"

    eval_cmd "ls /sys/devices/vdev"
    eval_cmd "ls /sys/devices/vdev/vdevice"

}

build_module
load_module
